<!--
 * @Author: wang cong wangc9832@163.com
 * @Date: 2023-06-08 09:17:07
 * @LastEditors: wang cong wangc9832@163.com
 * @LastEditTime: 2023-06-19 16:26:45
 * @FilePath: /ams-front/src/views/sys/role/RoleMenuDrawer.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    title="授权菜单"
    showFooter
    @ok="handleSubmit"
  >
    <BasicTree
      ref="grantTree"
      style="width: 300px"
      v-model:value="roleMenus"
      :treeData="treeData"
      :fieldNames="{ title: 'title', key: 'id' }"
      checkStrictly
      defaultExpandAll
      checkable
      toolbar
      title="菜单分配"
    />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { BasicTree, TreeActionType, TreeItem } from '@/components/Tree';
import { getMenuList, grantMenu, getGrantMenu } from '@/api/sys/system';
import { isArray } from 'xe-utils';
const emit = defineEmits(['success', 'register']);
const treeData = ref<TreeItem[]>([]);
const roleMenus = ref([]);

const roleData = ref();
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(
  async (data) => {
    setDrawerProps({ confirmLoading: false });
    treeData.value = (await getMenuList()) as any as TreeItem[];
    roleData.value = { ...data.record };
    const menus = await getGrantMenu(data.record.id);
    roleMenus.value = menus;
  }
);

const grantTree = ref<Nullable<TreeActionType>>(null);
async function handleSubmit() {
  try {
    setDrawerProps({ confirmLoading: true });
    const allChecked = unref(grantTree)?.getCheckedKeys();
    let grantMenuIdList;

    if (isArray(allChecked)) {
      grantMenuIdList = allChecked;
    } else {
      const { halfChecked, checked } = allChecked as unknown as {
        checked: string[];
        halfChecked: string[];
      };
      grantMenuIdList = [...halfChecked, ...checked];
    }
    await grantMenu({ roleId: roleData.value.id, menuIds: grantMenuIdList });

    closeDrawer();
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
